<?php
add_action('admin_footer', 'calculate_coupon_rate');

function calculate_coupon_rate()
{
?>
    <script type="text/javascript">

    jQuery(document).ready(function($)
    {
        /**
         * Disable input Display url when focus
         */
//        var input_display_url = "#display_url_metadata";
//        if($(input_display_url).length > 0)
//        {
//            $(input_display_url).css('background-color','whitesmoke');
//            $(input_display_url).focus(function(){
//                $(this).blur();
//            })
//        }
        /**
         * Script for calculate coupon rate
         */
        var txt_cp_rate = $('#cp_rate_metadata');
        // Function to set deley
        var delay = (function(){
            var timer = 0;
            return function(callback, ms){
            clearTimeout (timer);
            timer = setTimeout(callback, ms);
            };
        })();
        // Function calculate coupon rate
        function get_rate(like,dislike)
        {
            like = parseInt(like);
            dislike = parseInt(dislike);

            var temp = (like/(like + dislike)) * 100;
            var cp_rate = Math.round(temp);
            txt_cp_rate.val(cp_rate);
        }
        // Set coupon rate default
        var like = $('#like_metadata').val();
        var dislike = $('#dislike_metadata').val();
        if(!dislike)
        {
            $('#dislike_metadata').val('0');
            dislike = 0;
        }
        get_rate(like,dislike);
        // event text change
        $('#like_metadata').keyup(function(){
            var like = $(this).val();
            var dislike = $('#dislike_metadata').val();
            delay(function(){
                get_rate(like,dislike);

            }, 1000) // miliseconds

        }),
        // event text change
        $('#dislike_metadata').keyup(function(){
            var like = $('#like_metadata').val();
            var dislike = $(this).val();
            delay(function(){
                get_rate(like,dislike);
            }, 1000) // miliseconds

        }),
        // add link view store
        $('.select-wrapper').each(function(){
            if($(this).find('#store_coupon_metadata').length)
            {
                var st_id = $('#store_coupon_metadata').find(':selected').val();
                var st_name = $('#store_coupon_metadata').find(':selected').text();
                var st_url = "<span><a title='View store' href='<?php echo home_url('/?p=')?>" + st_id + "'>" + "View " + st_name + "</a></span>";

                //alert(st_url);
                $(this).append(st_url);
            }
        })
    });

    </script>
<?php
}
?>
